﻿#include "sndialog.h"
#include "ui_sndialog.h"
#include <QMessageBox>
 #include <QClipboard>
#include <QSettings>
SNDialog::SNDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SNDialog)
{
    ui->setupUi(this);
}

void SNDialog::setID(QString id)
{
    m_id = id;
    ui->label_ID->setText(id);
}

QString SNDialog::getSN()
{
    return ui->lineEditSN->text();
}

QString compute_sn(QString id)
{
    int x0 = id.at(0).unicode() + id.at(1).unicode()  + id.at(2).unicode()  +id.at(3).unicode() ;
    int x1 = id.at(5).unicode() + id.at(6).unicode()  + id.at(7).unicode()  +id.at(8).unicode() ;
    int x2 = id.at(10).unicode() + id.at(11).unicode()  + id.at(12).unicode()  +id.at(13).unicode() ;
    int x3 = id.at(15).unicode() + id.at(16).unicode()  + id.at(17).unicode()  +id.at(18).unicode() ;

    qDebug() << x0 << x1 << x2 << x3;

    QString ret;
    char c = x0 % 26 + 'A';
    ret.append(c);
    c = x1 % 26 + 'A';
    ret.append(c);
    c = x2 % 26 + 'A';
    ret.append(c);
    c = x3 % 26 + 'A';
    ret.append(c);

    return ret;

}

SNDialog::~SNDialog()
{
    delete ui;
}

void SNDialog::accept()
{

}

bool checkSN(QString id, QString sn)
{
    QString ssn = compute_sn(id);
    return sn == ssn;
}

void SNDialog::on_pushButtonCopy_clicked()
{
    QClipboard *clipboard = QGuiApplication::clipboard();
    clipboard->setText(m_id);
}

QString getRandomID()
{
    QString ret;

    for(int i = 0; i < 16; i++)
    {
        if(i != 0 && i % 4 == 0)
        {
            ret.append('-');
        }
        char x = rand() % 26 + 'A';
        ret.append(x);


    }
    return ret;
}

bool checkSN()
{
    QSettings settings("JingHai Technology", "JHPhotoV2");
    QString id = settings.value("System/ID", "").toString();
    if(id.isEmpty())
    {
        id = getRandomID();
        settings.setValue("System/ID", id);


        SNDialog dia;
        dia.setID(id);
        if(dia.exec() != QDialog::Accepted)
        {
            return false;
        }
        settings.setValue("System/SN", dia.getSN());
    }
    else
    {
        QString sn = settings.value("System/SN", "").toString();
        bool ok  = checkSN(id, sn);
        if(!ok )
        {
            SNDialog dia;
            dia.setID(id);
            if(dia.exec() != QDialog::Accepted)
            {
                return false;
            }
            settings.setValue("System/SN", dia.getSN());

        }
        else
        {
            return true;
        }
    }
}

void SNDialog::on_pushButton_clicked()
{
    QString sn = ui->lineEditSN->text();
    QString ssn = compute_sn(m_id);
    if(sn == ssn)
    {
        QDialog::accept();
    }
    else
    {
        QMessageBox::warning(this, u8"序列号错误", u8"序列号错误，请重新输入！");
        //QDialog::reject();
    }
}


void SNDialog::on_pushButtonReject_clicked()
{
    QDialog::reject();
}

